/**
 * @file rawSonDataDetail.js
 * @Date 2023-10-20, 周五, 14:8
 * @description 文件说明
 * 我的空间 原始资源部分 子资源管理表格 详情按钮弹窗的js
 */
$(function (){
    /******************************************初始化******************************************/
    const table=layui.table;
    const form=layui.form
    // 数据资源具体内容
    let contentDetailArr;
    // 获取URL中的查询参数部分
    const queryString = window.location.search;
    // 解析查询参数字符串，将其转换为对象
    const urlParams = new URLSearchParams(queryString);
    // 获取id参数的值
    const id = urlParams.get('id');
    // console.log('id', id)
    // 关键词列表cas
    let keywordCas=layui.layCascader(  {
        elem:`#keyWordSel`,
        clearable: true, // 显示清除按钮
        // options:data,
        filterable: true,
        props: {
            multiple: true, // 允许多选
            // strictMode:true//开启严格模式
        },
        // filterMethod:function (node,keyword){
        //     console.log('node,keyword', node,keyword)
        //     return true;
        // }
    })
    //分类列表cas
    let fieldTypeCas=layui.layCascader({
        elem:'#TypeSel',
        clearable:true,
        collapseTags: true,//折叠展示
        props:{
            multiple:true,
            lazy: true,
            lazyLoad:function (node,resolve){
                // console.log('node', node)
                const parentId=node?.data?.value
                $.ajax({
       timeout:30000,
                    url:window.Http+'/customer/fieldType/list',
                    type: 'GET',
                    headers: {
                        'Authorization': "Bearer " +  sessionStorage.getItem('Token')
                    },
                    contentType: 'application/x-www-form-urlencoded',
                    data: $.param({params:0,parentId:parentId,catalogTypes:"0,2"}),
                    success:function (res){
                        if (res.code===200){
                            let nodes=res.data.map(function (item) {
                                return {
                                    value: item.id,
                                    label: item.fieldName,
                                    leaf: !item.exitSon
                                };
                            })
                            resolve(nodes)
                        }else {
                            layer.msg('获取目录失败')
                        }
                    }
                })
            }
        }
    })
    // 数据通道列表cas
    let baseCas=layui.layCascader(  {
        elem:`#BaseSel`,
        clearable: true, // 显示清除按钮
        // options:data,
        filterable: true,
        props: {
            multiple: false, // 允许多选
            // strictMode:true//开启严格模式
        },
    })
    // 字段信息表格
    const fieldTable=table.render({
            elem: '#rawSonFiledTable'
            ,height: '.layui-tab-item'
            ,data:[]
            // ,page: true //开启分页
            ,cols: [[ //表头
                {type:'numbers', title: '序号', width:60}
                ,{field: 'columnName', title: '名称', width:120}
                ,{field: 'fieldAlias', title: '别名',templet:'#columnNickName'}
                ,{field: 'columnType', title: '类型'}
                ,{field: 'isUsing', title: '是否启用',templet: '#isUsing'}
                ,{field: 'remark', title: '备注',templet: '#remark'}
            ]]
        })
    /******************************************事件处理部分******************************************/
    // 提交审核按钮
    $('#submitAllForm').on('click',function (){
        const formData=form.val('rawSonForm');
        const submitData={
            "contentDetail":JSON.stringify(contentDetailArr) ,
            "contentName": formData.tableName,
            "contentNickName": formData.tableNickName,
            "controlRuleId": -1,
            "departInfo": formData.departInfo,
            "detail": formData.detail,
            "example": "",
            "firstType": "数据库",
            "iconUrl": "",
            "keywordList":keywordCas.getCheckedNodes().map(item=>item.data.label),
            "originSourceDependency":
                `{originDatasourceContentId:${id},
                originDatasourceContentName:${formData.tableName}}
                `,
            "secondType": "mysql",
            "sourceId": baseCas.getCheckedValues(),
            "status": 2,
            "typeIdList": fieldTypeCas.getCheckedValues()
        }
        $.ajax({
       timeout:30000,
            url: window.Http + "/datasourceContent/create",
            type: 'POST',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data:JSON.stringify(submitData),
            contentType:"application/json",
            success:function (res){
                if (res.code===200){
                    layer.msg('新增成功')
                    setTimeout(function(){
                        let index = parent.layer.getFrameIndex(window.name);
                        //执行关闭
                        parent.layer.close(index);
                        //window.parent.location.reload();
                    },1000)
                }else {
                    layer.msg(res.msg)
                }
            }
        })
    })
    // 保存按钮
    $('#cancelAllForm').on('click',function (){
        const formData=form.val('rawSonForm');
        const submitData={
            "contentDetail":JSON.stringify(contentDetailArr) ,
            "contentName": formData.tableName,
            "contentNickName": formData.tableNickName,
            "controlRuleId": -1,
            "departInfo": formData.departInfo,
            "detail": formData.detail,
            "example": "",
            "firstType": "数据库",
            "iconUrl": "",
            "keywordList":keywordCas.getCheckedNodes().map(item=>item.data.label),
            "originSourceDependency":
                `{originDatasourceContentId:${id},
                originDatasourceContentName:${formData.tableName}}
                `,
            "secondType": "mysql",
            "sourceId": baseCas.getCheckedValues(),
            "status": -1,
            "typeIdList": fieldTypeCas.getCheckedValues()
        }
        $.ajax({
            timeout:30000,
            url: window.Http + "/datasourceContent/create",
            type: 'POST',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data:JSON.stringify(submitData),
            contentType:"application/json",
            success:function (res){
                if (res.code===200){
                    layer.msg('保存成功')
                    setTimeout(function(){
                        let index = parent.layer.getFrameIndex(window.name);
                        //执行关闭
                        parent.layer.close(index);
                        //window.parent.location.reload();
                    },1000)
                }else {
                    layer.msg(res.msg)
                }
            }
        })
    })
    // 监听输入框输入按钮 别名
    $('.fieldTable').on('blur', '.columnNickName', function () {
        let id = Number($(this).attr('data-id')); //获取id
        let value = $(this).val(); //获取值
        console.log('id,value', id,value)
        const targetObject = contentDetailArr.find(obj => obj.id === id);

        if (targetObject) {
            targetObject.columnNickName = value;
        } else {
            layer.msg('该字段未找到')
        }
    });
    // 监听输入框输入按钮 备注
    $('.fieldTable').on('blur', '.remark', function () {
        let id = Number($(this).attr('data-id')); //获取id
        let value = $(this).val(); //获取值
        console.log('id,value', id,value)
        const targetObject = contentDetailArr.find(obj => obj.id === id);

        if (targetObject) {
            targetObject.remark = value;
        } else {
            layer.msg('该字段未找到')
        }
    });
    //监听输入框输入按钮 是否丢弃
    form.on('switch(isUsing)', function (obj) {
        let id = Number($(this).attr('data-id')); //获取id
        let value =  obj.elem.checked ? 1 : 0; //获取值
        // console.log('id,value', id,value)
        // console.log('contentDetailArr', contentDetailArr)
        const targetObject = contentDetailArr.find(obj => obj.id === id);

        if (targetObject) {
            targetObject.isUsing = value;
        } else {
            layer.msg('该字段未找到')
        }
    })
    /******************************************功能函数部分******************************************/
    /**
     * @description:请求原始数据子资源详情
     * @return {Promise} 请求的结果
     * @param id {String}
     */
    function rawSonDetailReq(id){
        return new Promise((function (resolve, reject) {
            $.ajax({
                timeout:30000,
                url: window.Http + `/datasourceTable/${id}`,
                type: 'GET',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                success: function (res) {
                    if (res.code===200){
                        resolve(res)
                    }else {
                        layer.msg(res.msg)
                        reject(new Error("请求失败")); // 失败时将错误传递给调用者
                    }
                }
            })
        }))
    }
   /**
    * @description:函数描述 请求关键字列表
    * @return {Promise} 请求的结果
    */
    function keywordListReq() {
        return new Promise(function (resolve, reject) {
            $.ajax({
                timeout:30000,
                url: window.Http + "/system/field/keyword",
                type: 'GET',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                data:{params:0,keyword:""},
                success:function (res){
                    if (res.code===200){
                        resolve(res)
                    }else {
                        layer.msg('获取关键字列表失败')
                        reject(new Error('错误'))
                    }
                }
            })
        })
    }
    /**
     * @description:函数描述 请求数据通道列表
     * @return {Promise} 请求的结果
     */
    function baseListReq(){
        return new Promise(function (resolve, reject){
            // 获取数据通道列表
            $.ajax({
                timeout:30000,
                url: window.Http + "/datasourceBase/list",
                type: 'GET',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                data:{ownUserId:sessionStorage.getItem('UserId'),status:0},
                success:function (res){
                    if (res.code===200){
                        resolve(res)
                    }else {
                        layer.msg('获取数据通道列表失败')
                        reject(new Error("请求失败")); // 失败时将错误传递给调用者
                    }
                }
            })
        })
    }

    /**
     * @description:函数描述 把数组转成级联选择器需要的格式
     * @return {Array} data 返回的数组
     * @param data {Array} 需要转换的数组
     * @param value {String}
     * @param label {String}
     * @param children {String}
     */
    function dataFormat(data,value,label,children=null){
        const propertyMap={}
        propertyMap[value]='value'
        propertyMap[label]='label'
        if (children){
            propertyMap[children]='children'
        }
        data.forEach(item=>renameProperties(item,propertyMap))
        return data
    }
    // 数据转换成级联列表需要的样式
    // data:原始数组，value:绑定的值（id），label：标签显示值，返回正确格式数组
    /**
     * @description:函数描述 数据转换成级联列表需要的样式
     * @return 返回值
     * @param obj
     * @param propertyMap
     */
    function renameProperties(obj,propertyMap){
        for (let key in obj) {
            if (obj[key] && typeof obj[key] === 'object') {
                renameProperties(obj[key], propertyMap);
            }
            if (propertyMap[key]) {
                obj[propertyMap[key]] = obj[key];
                delete obj[key];
            }
        }
    }
    // 初始化详情表单
    rawSonDetailReq(id).then(res=>{
        const data=res.data;
        contentDetailArr=data.datasourceFieldVoList;
        // console.log('data', data)
        data.isUsingIpt=data.isUsing===1?'是':'否'
        data.isShareIpt=data.isShare===1?'是':'否'
        data.isFreeIpt=data.isFree===1?'是':'否'
        form.val('rawSonForm',data);
        fieldTable.reload({data:data.datasourceFieldVoList})
    })
    // 关键字赋值
    keywordListReq().then(res=>{
        // keywordCas.setOptions(dataFormat(res.data.keywordList,'id','resourceName'))
        const optArr=res.data.map((item,index)=>{
            return {value:index,label:item}
        })
        keywordCas.setOptions(optArr)
    })
    baseListReq().then(res=>{
        baseCas.setOptions(dataFormat(res.rows,'id','resourceName'))
    })

})
